import { FileUtils } from './storage.file'

//先在这里定义变量
let fileUtils = {}

//========本地配置工具类========
//========本地配置工具类========
//========本地配置工具类========
export const localConfig = {
  config: null,
  //判断配置文件是否存在
  isFileExit: () => {
    console.log('isFileExit', localConfig.config)
    if (!(localConfig.config && typeof localConfig.config === 'object'))
      return fileUtils.initFileConfig
    return true
  },
  getItem: (key) => {
    const success = localConfig.isFileExit()
    console.log('getItem==>success', success)
    console.log('getItem==>localConfig.config', localConfig.config)
    if (success) {
      const result = localConfig.config[key]
      return result ? result : ''
    }
    return null
  },
  setItem: (key, value) => {
    let success = localConfig.isFileExit()
    if (success) {
      const config = Object.assign({}, localConfig.config)
      config[key] = value
      const suc = fileUtils.writeConfig(config)
      if (suc) {
        localConfig.config = config
        console.log('save local file success!')
        return true
      }
    }
    console.error('save local file error')
    return false
  },
  getAll: () => {
    let success = localConfig.isFileExit()
    if (success) {
      return localConfig.config
    }
    return null
  },
  removeItem: (key) => {
    const value = localConfig.getItem(key)
    if (value) {
      const config = Object.assign({}, localConfig.config)
      delete config[key]
      const suc = fileUtils.writeConfig(config)
      if (suc) {
        localConfig.config = config
        return true
      }
    }
    return false
  },
  clear: () => {
    let success = localConfig.isFileExit()
    if (success) {
      const suc = fileUtils.writeConfig({})
      if (suc) {
        localConfig.config = {}
        return true
      }
    }
    return false
  }
}

//再在这里实例化
fileUtils = new FileUtils()
